﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Quartz;
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using WorkerService.Common;
using WorkerService.Model.Send;

namespace WorkerService.Job
{
    [DisallowConcurrentExecution]
    public class InfraredJob : IJob
    {
        private readonly ILogger<InfraredJob> _logger;
        public InfraredJob(ILogger<InfraredJob> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 含Unicode字符转String
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string FromUnicodeString(string str)
        {
            //最直接的方法Regex.Unescape(str);
            StringBuilder strResult = new StringBuilder();
            if (!string.IsNullOrEmpty(str))
            {
                string[] strlist = str.Replace("\\", "").Split('u');
                try
                {
                    for (int i = 1; i < strlist.Length; i++)
                    {
                        int charCode = Convert.ToInt32(strlist[i], 16);
                        strResult.Append((char)charCode);
                    }
                }
                catch (FormatException ex)
                {
                    return Regex.Unescape(str);
                }
            }
            return strResult.ToString();
        }

        /// <summary>
        /// 红外同步作业
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Execute(IJobExecutionContext context)
        {
            _logger.LogInformation("红外作业开始");

            var time = DateTime.Now.AddHours(-1).ToString("yyyy/MM/dd HH:00:00");

            string[] all = Directory.GetDirectories(AppConfigurtaionServices.Configuration.GetSection("File").Value);//Directory.GetFiles(AppConfigurtaionServices.Configuration.GetSection("File").Value);
            for (int b = 0; b < all.Count(); b++)
            {
                var year = DateTime.Now.Year;
                var month = DateTime.Now.ToString("MM");
                var day = DateTime.Now.ToString("dd");

                var file = $"{all[b]}\\{year}年\\{month}月\\{day}日";
                if (Directory.Exists(file))
                {
                    var dirstr = Directory.GetFiles(file);

                    if (dirstr != null && dirstr.Count() > 0)
                    {
                        for (int i = 0; i < dirstr.Count(); i++)
                        {
                            if (dirstr[i].Contains("上传"))
                            {
                                _logger.LogInformation("红外图片上传中：" + dirstr[i]);

                                var result = HTTPHelper.HttpPostFile($"{AppConfigurtaionServices.Configuration.GetSection("Send").Value}Client/InfraredImg", dirstr[i]);
                                string imgAddress = FromUnicodeString(result);//处理中文乱码

                                var deviceId = all[b].Split("\\")[all[b].Split("\\").Length - 1];
                                var siteId = AppConfigurtaionServices.Configuration.GetSection("Site").Value;

                                InfraredModel model = new InfraredModel();

                                model.Img = imgAddress;
                                model.PointId = deviceId;
                                model.SiteId = siteId;
                                model.Createtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                                result = HTTPHelper.Client_Post($"{AppConfigurtaionServices.Configuration.GetSection("Send").Value}Client/InfraredAccept", JsonConvert.SerializeObject(model), "siteapp.workservice");
                               
                                #region 移动到上传文件夹内

                                if (result != "-1")
                                {
                                    var directory = dirstr[i].Split("\\");
                                    var directoryFile = string.Empty;
                                    for (int a = 0; a < directory.Count() - 1; a++)
                                    {
                                        directoryFile += directory[a] + "\\";
                                    }
                                    directoryFile += "上传";
                                    if (!Directory.Exists(directoryFile)) //判断上传文件夹是否存在，若不存在，则创建
                                    {
                                        Directory.CreateDirectory(directoryFile); //创建文件夹
                                    }
                                    if (!File.Exists(directoryFile + "\\" + dirstr[i].Split("\\")[dirstr[i].Split("\\").Count() - 1]))//文件
                                    {
                                        File.Copy(dirstr[i], directoryFile + "\\" + dirstr[i].Split("\\")[dirstr[i].Split("\\").Count() - 1]);
                                        if (File.Exists(directoryFile + "\\" + dirstr[i].Split("\\")[dirstr[i].Split("\\").Count() - 1]))
                                        {
                                            File.Delete(dirstr[i]);
                                        }
                                    }
                                    if (File.Exists(directoryFile + "\\" + dirstr[i].Split("\\")[dirstr[i].Split("\\").Count() - 1]))//文件
                                    {
                                        File.Delete(dirstr[i]);
                                    }
                                }


                                #endregion

                            }


                        }

                    }

                }

            }


            _logger.LogInformation("红外作业结束");

            return Task.CompletedTask;
        }
    }


}
